package com.cheetah.start.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.solon.plugins.pagination.Page;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import com.cheetah.start.common.base.query.PageQuery;
import com.cheetah.start.common.util.PasswordUtil;
import com.cheetah.start.module.system.domain.SysAdmin;
import com.cheetah.start.module.system.mapper.SysAdminMapper;
import com.cheetah.start.module.system.service.SysAdminService;
import com.cheetah.start.module.system.service.SysRoleAdminService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.List;

/**
 * @author Feel
 * @create 2021/7/18
 **/
@Component
public class SysAdminServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements SysAdminService {

    @Inject
    SysRoleAdminService roleAdminService;

    @Override
    public SysAdmin getByName(String name) {
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        return getOne(wrapper);
    }

    @Override
    public boolean saveWithRoleIds(SysAdmin sysAdmin) {
        save(sysAdmin);
        return roleAdminService.saveBySysAdmin(sysAdmin);
    }


    @Override
    public boolean updateByIdWithRole(SysAdmin sysAdmin) {
        if (StrUtil.isNotBlank(sysAdmin.getPassword())) {
            sysAdmin.setPassword(PasswordUtil.hash(sysAdmin.getPassword()));
        } else {
            sysAdmin.setPassword(null);
        }
        boolean b = updateById(sysAdmin);
        roleAdminService.removeByAdminId(sysAdmin.getAdminId());
        roleAdminService.saveBySysAdmin(sysAdmin);
        return b;
    }

    @Override
    public boolean isRepeat(SysAdmin sysAdmin) {
        QueryWrapper<SysAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("name", sysAdmin.getName());
        if (sysAdmin.getAdminId() != null) {
            wrapper.ne("admin_id", sysAdmin.getAdminId());
        }
        List<SysAdmin> list = list(wrapper);
        return CollUtil.isNotEmpty(list);
    }

    @Override
    public Page<SysAdmin> pageList(PageQuery pageQuery, SysAdmin admin) {
        Page<SysAdmin> pageInfo = new Page<>(pageQuery.getPage(), pageQuery.getLimit());
        QueryWrapper<SysAdmin> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        qw.like(StrUtil.isNotBlank(admin.getName()), "name", admin.getName());
        qw.like(StrUtil.isNotBlank(admin.getRealName()), "real_name", admin.getRealName());
        page(pageInfo, qw);
        return pageInfo;
    }
}
